﻿using QLCONGNOAPPs.Commons;
using QLCONGNOAPPs.UserForms.DungDD_UserForm.userForm_DanhMucToChuc_DungDD;
using QLCONGNOLIBS.Controllers.DungDD_Controller;
using QLCONGNOLIBS.Securities.DungDD_SecurityFramework;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraPrinting;
using QLCONGNOAPPs.BaseControls.DungDD_BC;
using QLCONGNOLIBS.Ultils;

namespace QLCONGNOAPPs.UserControls.DungDD_UC.UC_DanhMucToChuc_DungDD
{
    public partial class uc_PhongBan_DungDD : UserControl
    {
        //datafield
        private SqlConnection objConnection_g;
        private Commons.Services objServices_g;
        //
        private tblUser_SC objUserSc_g;
        private IDepartment_Controller_DungDD objDepartmentController_g;
        private string departmentID_MemoEdit;

        private string trangThaiPB = "All"; // biến định nghĩa trạng thái load table

        public uc_PhongBan_DungDD()
        {
            InitializeComponent();
            //
            //   departmentID_MemoEdit = new Guid();
            //  khởi tạo các sự kiện
            baseControl_D1.PressNew += baseControl_D1_PressNew;
            baseControl_D1.PressEdit += baseControl_D1_PressEdit;
            baseControl_D1.PressDelete += baseControl_D1_PressDelete;
            baseControl_D1.PressPrint += baseControl_D1_PressPrint;
            baseControl_D1.PressRefresh += baseControl_D1_PressRefresh;
            baseControl_D1.PressRestore += baseControl_D1_PressRestore;
            baseControl_D1.PressHelp += baseControl_D1_PressHelp;

            //Kết nối
            objConnection_g = new SqlConnection();
            objServices_g = new Services();
            objConnection_g = objServices_g.getConnection();

            // truyền tham số cho controller
            objUserSc_g = new tblUser_SC();
            objDepartmentController_g = new IDepartment_Controller_DungDD(objConnection_g, objUserSc_g);
        }
        /// <summary>
        /// trợ giúp
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressHelp(object sender, EventArgs e)
        {
            if (MessageBox.Show(@"Truy cập đến http://www.imic.edu.vn/ để được trợ giúp?", "Trợ giúp?", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
            {
                System.Diagnostics.Process.Start("http://www.imic.edu.vn/");
            }
        }

        /// <summary>
        /// Khôi phục bản ghi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressRestore(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string departmentID = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");
                if (!string.IsNullOrEmpty(departmentID))
                {
                    var index = gridView_PhongBan.GetFocusedDataSourceRowIndex();
                    Guid departmentIdGuid = Guid.Parse(departmentID);

                    var message = MessageBox.Show("Bạn muốn khôi phục bản ghi này?", "Khôi phục bản ghi?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (message == DialogResult.Yes)
                    {
                        bool isDeleted = false;
                        objDepartmentController_g.UpdateDepartmentStatus_ByID_C(departmentIdGuid, isDeleted);
                        LoadPhongBan();
                        gridView_PhongBan.FocusedRowHandle = gridView_PhongBan.GetRowHandle(index);
                    }
                    else
                    {
                    }
                }
                else
                {
                    MessageBox.Show("Vui lòng chọn 1 bản ghi cần xóa", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// refresh phong ban table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressRefresh(object sender, EventArgs e)
        {
            LoadPhongBan();
        }

        private void baseControl_D1_PressPrint(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                gridControl_phongBan.ShowPrintPreview();

                //// gridControl_phongBan.ShowPrintPreview();
                //PrintableComponentLink pcl = new PrintableComponentLink(printingSystem1);

                //pcl.Component = gridControl_phongBan;


                //PageHeaderFooter phf = pcl.PageHeaderFooter as PageHeaderFooter;

                //// Clear the PageHeaderFooter's contents.
                //phf.Header.Content.Clear();

                //// Add custom information to the link's header.
                //phf.Header.Content.AddRange(new string[] { string.Empty, "TITLE", "[Date Printed] [Time Printed]" });
                //phf.Header.LineAlignment = BrickAlignment.Far;



                ////pcl.CreateDocument();
                //pcl.ShowPreviewDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Bắt sự kiện delete bản ghi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressDelete(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string departmentID = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");
                if (!string.IsNullOrEmpty(departmentID))
                {
                    if (trangThaiPB.Equals("All"))
                    {
                        var index = gridView_PhongBan.GetFocusedDataSourceRowIndex();
                        Guid departmentIdGuid = Guid.Parse(departmentID);

                        var message = MessageBox.Show("Bạn muốn xóa bản ghi này?", "Xóa bản ghi?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (message == DialogResult.Yes)
                        {
                            bool isDeleted = true;
                            objDepartmentController_g.UpdateDepartmentStatus_ByID_C(departmentIdGuid, isDeleted);
                            LoadPhongBan();
                            gridView_PhongBan.FocusedRowHandle = gridView_PhongBan.GetRowHandle(index);
                        }
                    }
                    else if (trangThaiPB.Equals("deleted"))
                    {
                        var index = gridView_PhongBan.GetFocusedDataSourceRowIndex();
                        Guid departmentIdGuid = Guid.Parse(departmentID);

                        var message = MessageBox.Show("Bạn muốn xóa vĩnh viễn bản ghi này?", "Xóa vĩnh viễn bản ghi?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (message == DialogResult.Yes)
                        {
                            objDepartmentController_g.DeleteDepartment_ByID_C(departmentIdGuid);LoadPhongBan();
                            gridView_PhongBan.FocusedRowHandle = gridView_PhongBan.GetRowHandle(index);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Vui lòng chọn 1 bản ghi cần xóa", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// bắt sự kiện "Cập nhật"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressEdit(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string departmentID = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");
                if (!string.IsNullOrEmpty(departmentID))
                {
                    var index = gridView_PhongBan.GetFocusedDataSourceRowIndex();
                    string flag = "sua";
                    Guid departmentIdGuid = Guid.Parse(departmentID);
                    string departmentName = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentName");
                    bool isdeleted = bool.Parse("" + gridView_PhongBan.GetFocusedRowCellValue("isDeleted"));
                    string departmentNote = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
                    IDepartment_Entity objEntity = new IDepartment_Entity(departmentIdGuid, departmentName, isdeleted, departmentNote);
                    AddUpdate_PhongBan objAddUpdatePhongBan = new AddUpdate_PhongBan(objConnection_g, objUserSc_g, objEntity, flag);
                    objAddUpdatePhongBan.ShowDialog();
                    LoadPhongBan();
                    //Định vị row của bảng
                    gridView_PhongBan.FocusedRowHandle = gridView_PhongBan.GetRowHandle(index);
                    //quick note
                    memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
                    departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");
                }
                else
                {
                    MessageBox.Show("Vui lòng chọn 1 bản ghi cần cập nhật", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// Bắt sửa kiện "Thêm"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void baseControl_D1_PressNew(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string flag = "them";
                IDepartment_Entity objEntity = new IDepartment_Entity(Guid.NewGuid(), "", false, "");
                AddUpdate_PhongBan objPhongBan = new AddUpdate_PhongBan(objConnection_g, objUserSc_g, objEntity, flag);
                objPhongBan.ShowDialog();
                LoadPhongBan();
                FocusNewRow("" + objEntity.DepartmentIdP);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw ex;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Focus new row  have added
        /// </summary>
        /// <param name="departmentID"></param>
        public void FocusNewRow(string departmentID)
        {
            int rowindex = 0;
            for (int i = 0; i < gridView_PhongBan.RowCount; i++)
            {
                string dataCell = "" + gridView_PhongBan.GetRowCellValue(i, "DepartmentID");
                if (departmentID.Equals(dataCell))
                {
                    rowindex = i;
                }
            }
            gridView_PhongBan.FocusedRowHandle = rowindex;

        }
        /// <summary>
        /// Load phòng ban table
        /// </summary>
        public void LoadPhongBan()
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                DataTable objTable = new DataTable();
                objTable = objDepartmentController_g.GetDepartmentDataTable(trangThaiPB);
                gridControl_phongBan.DataSource = objTable;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Chi tiết: " + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// Bắt sự kiện uc_PhongBan_DungDD_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uc_PhongBan_DungDD_Load(object sender, EventArgs e)
        {

            LoadPhongBan();
            BaseControl_D objuc = new BaseControl_D();
            baseControl_D1.disableBtnKhoiPhuc();
            //set focus NavBarItem
            Ultis_DungDD.Instance.FocusNavBarItem(navBarItem_All);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ThungRac);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ChuaThietLap);
        }

        /// <summary>
        /// Bắt sự kiện RowCellClick của gridView_PhongBan
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_PhongBan_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            // quick note
            memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
            departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");

        }

        /// <summary>
        /// Bắt sự kiện memoEdit_GhiChu_Leave
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void memoEdit_GhiChu_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(departmentID_MemoEdit))
            {
                var index = gridView_PhongBan.GetFocusedDataSourceRowIndex();

                Guid departID = new Guid();
                departID = Guid.Parse(departmentID_MemoEdit);
                string new_note = memoEdit_GhiChu.Text.Trim();
                objDepartmentController_g.Update_note_department_C(departID, new_note);
                LoadPhongBan();

                gridView_PhongBan.FocusedRowHandle = gridView_PhongBan.GetRowHandle(index);
            }

        }
        /// <summary>
        /// Băt sự kiện rowclick của gridView_PhongBan
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_PhongBan_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            // quick note
            memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
            departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");

        }

        private void navBarItem_All_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            trangThaiPB = "All";
            LoadPhongBan();
            baseControl_D1.disableBtnKhoiPhuc();
            // quick note
            memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
            departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");

            //set focus NavBarItem
            Ultis_DungDD.Instance.FocusNavBarItem(navBarItem_All);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ThungRac);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ChuaThietLap);

        }

        private void navBarItem_ChuaThietLap_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {

            trangThaiPB = "notset";
            LoadPhongBan();
            baseControl_D1.disableBtnKhoiPhuc();
            // quick note
            memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
            departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");

            //set focus NavBarItem
            Ultis_DungDD.Instance.FocusNavBarItem(navBarItem_ChuaThietLap);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_All);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ThungRac);

        }

        private void navBarItem_ThungRac_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            trangThaiPB = "deleted";
            LoadPhongBan();
            baseControl_D1.enableBtnLhoiPhuc();
            // quick note
            memoEdit_GhiChu.Text = "" + gridView_PhongBan.GetFocusedRowCellValue("Note");
            departmentID_MemoEdit = "" + gridView_PhongBan.GetFocusedRowCellValue("DepartmentID");

            //set focus NavBarItem 
            Ultis_DungDD.Instance.FocusNavBarItem(navBarItem_ThungRac);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_All);
            Ultis_DungDD.Instance.Non_FocusNavBarItem(navBarItem_ChuaThietLap);

        }

        private void gridView_PhongBan_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            GridCellInfo ci = e.Cell as GridCellInfo;
            string str = e.DisplayText;
            SizeF strSize = e.Graphics.MeasureString(e.DisplayText, e.Appearance.GetFont(), ci.CellValueRect.Width - 1, e.Appearance.GetStringFormat());
            if (strSize.Height <= ci.CellValueRect.Height) return;
            while (strSize.Height >= ci.CellValueRect.Height)
            {
                str = str.Remove(str.Length - 1);
                strSize = e.Graphics.MeasureString(str + "...", e.Appearance.GetFont(), ci.CellValueRect.Width - 1, e.Appearance.GetStringFormat());
            }
            e.Appearance.DrawString(e.Cache, str + "...", e.Bounds);

            e.Handled = true;
        }

      


    }
}